import os
import sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from utils.toml import load_mysql_config
from dao.orm import DBManager
from utils.time import subtract_time

mysql_config = load_mysql_config("./config/config.toml")

db = DBManager(
    mysql_config["host"],
    mysql_config["user"],
    mysql_config["password"],
    mysql_config["database"]
)

class classRecord:
    def __init__(self):
        db.connect()

    # 写入记录
    def insert_cord(self, exam):
        return db.insert('exam_record', exam)

    # 根据考试名称获取考试签到条数
    def get_class_count(self, exam):
        res =  db.fetchone("SELECT count(*) FROM `exam_record` WHERE exam_name = %s", (exam,))
        if not res:
            return 0
        return res
    
    def get_class(self, student):
        return db.fetchall("SELECT * FROM `exam_record` WHERE student_name = %s", (student,))
    
    def get_record_by_student(self,student_name, class_name):
        return db.fetchall("SELECT * FROM `exam_record` WHERE student_name = %s AND exam_class = %s", (student_name, class_name))

    # 导出缺勤名单
    def export_absence(self, exam, class_name):
        # 获取该考试名称的所有考试
        records = db.fetchall("SELECT * FROM `exam_record` WHERE exam_name = %s AND exam_class = %s", (exam, class_name))
        if not records: return []
        # 获取所有学生
        students = [i for i in records if subtract_time(i['sign_in_time'], i['exam_start_time']) > 15]
        return students
    
    def export_data(self, exam, class_name):
        # 获取该考试名称的所有考试
        records = db.fetchall("SELECT * FROM `exam_record` WHERE exam_name = %s AND exam_class = %s", (exam, class_name))
        if not records: return []
        return records
    
    # 导出迟到名单
    def export_late(self, exam):
        # 获取该考试名称的所有考试
        records = db.fetchall("SELECT * FROM `exam_record` WHERE exam_name = %s", (exam,))
        if not records: return []
        # 获取所有学生
        students = [i for i in records if 0 < subtract_time(i['sign_in_time'], i['exam_start_time']) <= 0]
        return students